<template>
  <div class="follow-container">
    <div class="container py-4">
      <!-- 页面标题 -->
      <div class="row mb-4">
        <div class="col">
          <h2 class="mb-0">关注与粉丝</h2>
          <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
              <li class="breadcrumb-item">
                <a href="#" @click.prevent="$router.push('/user/profile')">个人中心</a>
              </li>
              <li class="breadcrumb-item active" aria-current="page">关注与粉丝</li>
            </ol>
          </nav>
        </div>
      </div>

      <!-- 标签页 -->
      <ul class="nav nav-tabs mb-4">
        <li class="nav-item">
          <a class="nav-link" :class="{ active: activeTab === 'following' }" @click="activeTab = 'following'" href="#">
            <img src="@/assets/images/Follow/关注.svg" width="16" height="16" class="me-1" alt="关注图标">
            <span :class="{ 'text-primary': activeTab === 'following', 'text-dark': activeTab !== 'following' }">关注</span>
            <span class="badge bg-primary ms-1">{{ following.length }}</span>
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" :class="{ active: activeTab === 'followers' }" @click="activeTab = 'followers'" href="#">
            <img src="@/assets/images/Follow/粉丝.svg" width="16" height="16" class="me-1" alt="粉丝图标">
            <span :class="{ 'text-primary': activeTab === 'followers', 'text-dark': activeTab !== 'followers' }">粉丝</span>
            <span class="badge ms-1" style="background-color: #ff69b4; color: white;">{{ followers.length }}</span>
          </a>
        </li>
      </ul>

      <!-- 错误提示 -->
      <div v-if="error" class="alert alert-danger" role="alert">
        <h4 class="alert-heading">加载失败!</h4>
        <p>{{ error }}</p>
        <hr>
        <button class="btn btn-outline-danger" @click="fetchData">重新加载</button>
      </div>

      <!-- 加载状态 -->
      <div v-else-if="loading" class="d-flex justify-content-center my-5">
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">加载中...</span>
        </div>
        <span class="ms-2">正在加载数据...</span>
      </div>

      <!-- 内容容器 -->
      <div class="content-container" style="height: 600px; overflow-y: auto;">
        <!-- 关注列表 -->
        <div v-if="activeTab === 'following'">
          <div v-if="following.length === 0" class="text-center py-5">
            <div class="text-muted mb-3">
              <i class="bi bi-people fs-1"></i>
            </div>
            <h5 class="text-muted">暂无关注用户</h5>
            <p class="text-muted">快去发现有趣的人并关注吧</p>
            <button class="btn btn-primary" @click="$router.push('/')">去发现</button>
          </div>
          
          <div v-else>
            <div class="row">
              <transition-group name="card" tag="div" class="row">
                <div v-for="user in following" :key="user.id" class="col-12 mb-4">
                  <div class="card h-100 shadow-sm">
                    <div class="row g-0">
                      <div class="col-md-3 d-flex align-items-center">
                        <img :src="user.avatar || '@/assets/images/default-avatar.jpg'" class="img-fluid rounded-start h-100 object-fit-cover" alt="用户头像" style="height: 150px; width: 100%; object-fit: cover;" @error="handleImageError($event)">
                      </div>
                      <div class="col-md-9">
                        <div class="card-body">
                          <h5 class="card-title">
                            <a href="#" @click.prevent="goToUser(user.followingId)" class="text-decoration-none">
                              {{ user.nickname }}
                            </a>
                          </h5>
                          <p class="card-text">{{ user.bio || '这个用户还没有个人简介' }}</p>
                          <div class="d-flex justify-content-between text-muted mb-2">
                            <span>关注时间：{{ formatDate(user.createdAt) }}</span>
                          </div>
                          <div class="d-flex justify-content-between align-items-center mt-3">
                            <button class="btn btn-sm btn-outline-primary" @click="goToUser(user.followingId)">
                              <i class="bi bi-person"></i> 查看资料
                            </button>
                            <button class="btn btn-sm btn-outline-danger" @click="unfollow(user.id)">
                              <i class="bi bi-x-lg"></i> 取消关注
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </transition-group>
            </div>
          </div>
        </div>

        <!-- 粉丝列表 -->
        <div v-else-if="activeTab === 'followers'">
          <div v-if="followers.length === 0" class="text-center py-5">
            <div class="text-muted mb-3">
              <i class="bi bi-people fs-1"></i>
            </div>
            <h5 class="text-muted">暂无粉丝</h5>
            <p class="text-muted">多多互动，吸引更多粉丝吧</p>
            <button class="btn btn-primary" @click="$router.push('/')">去发现</button>
          </div>
          
          <div v-else>
            <div class="row">
              <transition-group name="card" tag="div" class="row">
                <div v-for="user in followers" :key="user.id" class="col-12 mb-4">
                  <div class="card h-100 shadow-sm">
                    <div class="row g-0">
                      <div class="col-md-3 d-flex align-items-center">
                        <img :src="user.avatar || '@/assets/images/头像加载失败.jpg'" class="img-fluid rounded-start h-100 object-fit-cover" alt="用户头像" style="height: 150px; width: 100%; object-fit: cover;" @error="handleImageError($event)">
                      </div>
                      <div class="col-md-9">
                        <div class="card-body">
                          <h5 class="card-title">
                            <a href="#" @click.prevent="goToUser(user.followerId)" class="text-decoration-none">
                              {{ user.nickname }}
                            </a>
                          </h5>
                          <p class="card-text">{{ user.bio || '这个用户还没有个人简介' }}</p>
                          <div class="d-flex justify-content-between text-muted mb-2">
                            <span>成为粉丝时间：{{ formatDate(user.createdAt) }}</span>
                          </div>
                          <div class="d-flex justify-content-between align-items-center mt-3">
                            <button class="btn btn-sm btn-outline-primary" @click="goToUser(user.followerId || user.id)">
                              <i class="bi bi-person"></i> 查看资料
                            </button>
                            <button v-if="!user.isFollowing" class="btn btn-sm btn-primary" @click="follow(user.id)">
                              <i class="bi bi-person-plus"></i> 关注
                            </button>
                            <button v-else class="btn btn-sm btn-outline-secondary" disabled>
                              <i class="bi bi-check"></i> 已关注
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </transition-group>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getFollowingListService, 
          getFollowerListService,
          UnfollowService,
          FollowService } from '@/api/Follow.js'

import { getUserInfoByIdService } from '@/api/user.js'
import useUserInfoStore from '@/stores/userInfo.js'

const userInfoStore = useUserInfoStore()
const router = useRouter()

// 用户信息
const userInfo = userInfoStore

// 活跃标签页
const activeTab = ref('following')

// 关注列表
const following = ref([])

// 粉丝列表
const followers = ref([])

// 加载状态
const loading = ref(true)

// 错误信息
const error = ref(null)

// 获取关注和粉丝列表
const fetchData = async () => {
  try {
    loading.value = true
    error.value = null
    
    // 获取关注列表
    const followingRes = await getFollowingListService(userInfo.info.id)
    following.value = followingRes.data || []
    console.log('获取关注列表:', followingRes.data)
    
    // 为关注列表中的每个用户获取详细信息
    if (following.value.length > 0) {
        //Promise.all() 等待所有异步操作完成
      following.value = await Promise.all(following.value.map(async (followItem) => {
        try {
          const userInfoRes = await getUserInfoByIdService(followItem.followingId)
          return {
            ...followItem,
            ...userInfoRes.data
          }
          
        } catch (err) {
          console.error(`获取用户 ${followItem.followingId} 信息失败:`, err)
          return followItem
        }
      }))
    }
    console.log('关注列表详细信息:', following.value)
    // 获取粉丝列表
    const followersRes = await getFollowerListService(userInfo.info.id)
    followers.value = followersRes.data || []
    console.log('获取粉丝列表:', followersRes.data)

    // 为粉丝列表中的每个用户获取详细信息
    if (followers.value.length > 0) {
      followers.value = await Promise.all(followers.value.map(async (followerItem) => {
        try {
          const userInfoRes = await getUserInfoByIdService(followerItem.followerId)
          return {
            ...followerItem,
            ...userInfoRes.data
          }
        } catch (err) {
          console.error(`获取用户 ${followerItem.followerId} 信息失败:`, err)
          return followerItem
        }
      }))
    }
    console.log('粉丝列表详细信息:', followers.value)   
    // 为粉丝列表添加是否已关注的标记
    followers.value = followers.value.map(follower => ({
      ...follower,
      isFollowing: following.value.some(followingUser => followingUser.id === follower.id)
    }))

  } catch (err) {
    console.error('获取数据失败:', err)
    error.value = `获取数据失败: ${err.message || '未知错误'}`
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 跳转到用户详情
const goToUser = (id) => {
  router.push(`/user/Detail/${id}`)
}

// 处理图片加载错误
const handleImageError = (event) => {
  event.target.src = new URL('@/assets/images/头像加载失败.jpg', import.meta.url).href
}

// 取消关注
const unfollow = (userId) => {
  ElMessageBox.confirm('确定要取消关注吗？', '确认操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await UnfollowService(userId)
      // 从关注列表中移除
      following.value = following.value.filter(user => user.id !== userId)
      // 更新粉丝列表中的关注状态
      followers.value = followers.value.map(user => {
        if (user.id === userId) {
          return { ...user, isFollowing: false }
        }
        return user
      })
      ElMessage.success('已取消关注')
    } catch (err) {
      console.error('取消关注失败:', err)
      ElMessage.error('取消关注失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 关注用户
const follow = (followerId) => {
  ElMessageBox.confirm('确定要关注该用户吗？', '确认操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await FollowService(followerId)
      // 更新粉丝列表中的关注状态
      followers.value = followers.value.map(user => {
        if (user.id === followerId) {
          return { ...user, isFollowing: true }
        }
        return user
      })
      // 重新获取关注列表
      fetchData()

      ElMessage.success('已关注用户')
    } catch (err) {
      console.error('关注失败:', err)
      ElMessage.error('关注失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 初始化数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.follow-container {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding-top: 20px;
}

.nav-tabs .nav-link {
  cursor: pointer;
  border: none;
  background-color: transparent;
  transition: all 0.3s ease;
}

.nav-tabs .nav-link:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.nav-tabs .nav-link.active {
  border-bottom: 2px solid #0d6efd;
  font-weight: 500;
}

.card {
  transition: all 0.3s ease;
  transform: translateY(0);
  opacity: 1;
}

.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
}

.breadcrumb {
  background-color: transparent;
  padding: 0;
}

.breadcrumb-item a {
  text-decoration: none;
  color: #6c757d;
  transition: color 0.2s ease;
}

.breadcrumb-item a:hover {
  color: #0d6efd;
}

.breadcrumb-item.active {
  color: #495057;
}

/* 淡入淡出过渡效果 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

/* 滑动淡出过渡效果 */
.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from {
  transform: translateX(20px);
  opacity: 0;
}

.slide-fade-leave-to {
  transform: translateX(-20px);
  opacity: 0;
}

/* 卡片入场动画 */
.card-enter-active {
  transition: all 0.5s ease;
}

.card-enter-from {
  opacity: 0;
  transform: translateY(30px);
}

.card-enter-to {
  opacity: 1;
  transform: translateY(0);
}

/* 标签页过渡效果 */
.tab-content > .tab-pane {
  display: block;
}

.tab-content > .tab-pane:not(.active) {
  display: none;
}

/* 加载动画 */
.spinner-border {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 内容容器滚动条样式 */
.content-container::-webkit-scrollbar {
  width: 8px;
}

.content-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.content-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.content-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>